package com.pig4cloud.pig.ads.gdt.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.ads.gdt.service.GdtAdvertiserService;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAccesstokenMapper;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAdvertiserMapper;
import com.pig4cloud.pig.ads.service.AdAccountService;
import com.pig4cloud.pig.ads.service.AdvertiserService;
import com.pig4cloud.pig.api.entity.AccountToken;
import com.pig4cloud.pig.api.gdt.entity.GdtAccesstoken;
import com.pig4cloud.pig.api.util.Constants;
import com.pig4cloud.pig.api.util.RandomUtil;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@Service
@RequiredArgsConstructor
public class GdtAccesstokenServiceImpl extends ServiceImpl<GdtAccesstokenMapper, GdtAccesstoken> implements GdtAccesstokenService {

	private final StringRedisTemplate stringRedisTemplate;

	private final AdvertiserService advertiserService;

	private final GdtAccesstokenMapper gdtAccesstokenMapper;


	/**
	 * @根据管家账户获取公共信息
	 */
	@Override
	public Map<String, String> findGdtCommonData(String accountId){
		Map<String, String> map = new HashMap<>();
		map.put("access_token", findAccessToken(accountId));
		map.put("timestamp", String.valueOf(System.currentTimeMillis()/1000));
		map.put("nonce", RandomUtil.generateLetterStr(32));
		return map;
	}


	@Override
	public void saveUpdateList(List<GdtAccesstoken> list){
		if(CollectionUtils.isNotEmpty(list)){
			this.saveOrUpdateBatch(list,1000);
		}
	}

	/**
	 * @通过管家账户获取accessToken
	 * @param accountId
	 * @return
	 */
	public String findAccessToken(String accountId){
		try {
			//判断redis是否有token缓存
			String tokenContent = stringRedisTemplate.opsForValue().get(Constants.GDT_REDIS_TOKEN_KEY_PRIX_ + accountId);
			if(StringUtils.isBlank(tokenContent) || "null".equals(tokenContent)) { //redis为空
				//查找数据库是否有
				GdtAccesstoken entity = gdtAccesstokenMapper.selectById(accountId);
				if( entity == null ) { //数据库没有，返回null
					return null;
				}else {
					return entity.getAccessToken();
				}
			}else {
				GdtAccesstoken accessToken = JSON.parseObject(tokenContent, GdtAccesstoken.class);
				return accessToken.getAccessToken();
			}
		} catch (Exception e) {
			log.error("获取gdtaccesstoken出错", e);
		} catch (Throwable e) {
			log.error("获取gdtaccesstoken出错", e);
		}
		return null;
	}

	/**
	 * @通过普通账户获取公共信息
	 */
	@Override
	public Map<String, String> fetchAccesstoken(String adAccount) {
		Map<String, String> map = new HashMap<>();
		if(StringUtils.isBlank(adAccount)) {
			return map;
		}
		AccountToken adv = advertiserService.getAdvertiserToken(PlatformTypeEnum.GDT.getValue(),adAccount);
		if(adv == null || StringUtils.isBlank(adv.getHousekeeper())) {
			return map;
		}
		map.put("access_token", adv.getAccessToken());
		map.put("timestamp", String.valueOf(System.currentTimeMillis()/1000));
		map.put("nonce", RandomUtil.generateLetterStr(32));
		return map;
	}

}
